#!/usr/bin/env python
import fileinput
import sys
import scrap
import pdb
import os
from scrap import no, empty, flatten

args = sys.argv[1:]
if len(args) <= 0:
    pass


exclude=[]
include=[]
exclude_bang=[]
include_bang=[]
invert=False
recursive=False

for arg in args:
    if arg == '%noext':
        # include files without extensions
        arg = r'/[^.]\+$'

    elif arg == '-r' or arg == '--recurse' or arg == '--recursive': 
        recursive = True
        continue

    if arg == '-v':
        invert = True

    elif invert:
        if arg.startswith('#!'):
            exclude_bang += [arg[2:]]
        else:
            exclude += [arg]
        invert = False

    else:
        if arg.startswith('#!'):
            include_bang += [arg[2:]]
        else:
            include += [arg]

lines = []
output = scrap.shell('find . -type f')

if not recursive:
    # exclude files in subdirectories
    output = scrap.system('grep', ['-v'] + [['-e', pattern] for pattern in [r'/.*/.*$']], output)

files = output

if not empty(exclude):
    output = scrap.system('grep', ['-v'] + [['-e', pattern] for pattern in exclude], output)

if not empty(include):
    lines += [scrap.system('grep', [['-e', pattern] for pattern in include], output)]

if not empty(include_bang):
    for pattern in include_bang:
        lines += [scrap.system('hasbang', [pattern] + files.splitlines())]

if not empty(exclude_bang):
    assert(False) # not yet implemented

if empty(include) and empty(include_bang):
    lines = [output]

# remove dupes.
dup = set()
final = []
for x in lines:
    if x not in dup:
        dup.add(x)
        final.append(x)


output = scrap.system('sort-cppfiles', [], stdin='\n'.join(final))

#output = scrap.system('sortuniq', [], stdin='\n'.join(final))
#output = '\n'.join(final)

sys.stdout.write(output)

